package logger

import (
	"fmt"
	"github.com/fatih/color"
	"github.com/sirupsen/logrus"
	"strconv"
	"time"
)

var Logger *logrus.Logger

func LogInit() {
	Logger = logrus.New()
	// 设置自定义格式化程序
	Logger.Formatter = &CustomTextFormatter{
		ForceColors:   true,
		ColorInfo:     color.New(color.FgBlue),
		ColorWarning:  color.New(color.FgYellow),
		ColorError:    color.New(color.FgRed),
		ColorCritical: color.New(color.BgRed, color.FgWhite),
	}
}

type CustomTextFormatter struct {
	ForceColors   bool         // 强制使用颜色
	ColorInfo     *color.Color // Info级别日志颜色
	ColorWarning  *color.Color // Warn级别日志颜色
	ColorError    *color.Color // Error级别日志颜色
	ColorCritical *color.Color // Critical级别日志颜色
}

// Format 自定义Format方法
func (f *CustomTextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	//fmt.Println("entry.Level", entry.Level)
	if f.ForceColors {
		// 如果强制使用颜色，则根据日志级别打印带有颜色的输出
		switch entry.Level {
		case logrus.InfoLevel:
			f.ColorInfo.Println(formatMessageWithTimestamp(entry))
		case logrus.WarnLevel:
			f.ColorWarning.Println(formatMessageWithTimestamp(entry))
		case logrus.ErrorLevel:
			f.ColorError.Println(formatMessageWithTimestamp(entry))
		case logrus.FatalLevel, logrus.PanicLevel:
			f.ColorCritical.Println(formatMessageWithTimestamp(entry))
		default:
			f.PrintColored(entry)
		}
		return nil, nil
	} else {
		// 否则，返回默认格式化输出
		return f.formatDefault(entry)
	}
}

// 格式化默认输出的方法
func (f *CustomTextFormatter) formatDefault(entry *logrus.Entry) ([]byte, error) {
	timestamp := entry.Time.Format(time.DateTime)
	level := entry.Level.String()
	msg := entry.Message

	return []byte(fmt.Sprintf("[%s] %s %s\n", level, timestamp, msg)), nil
}

// PrintColored 打印带颜色的日志输出的方法
func (f *CustomTextFormatter) PrintColored(entry *logrus.Entry) {
	levelColor := color.New(color.FgCyan, color.Bold)
	levelText := levelColor.Sprintf("%-6s", entry.Level.String())

	msg := levelText + " " + formatMessageWithTimestamp(entry)
	if entry.HasCaller() {
		msg += " (" + entry.Caller.File + ":" + strconv.Itoa(entry.Caller.Line) + ")"
	}

	fmt.Fprintln(color.Output, msg)
}

// 格式化消息并添加时间戳
func formatMessageWithTimestamp(entry *logrus.Entry) string {
	timestamp := entry.Time.Format(time.DateTime)
	level := entry.Level.String()
	return "[" + level + "]" + timestamp + " " + entry.Message
}

func main2() {
	LogInit()
	//color.RGB(255, 128, 0).Println("foreground orange")
	//color.RGB(230, 42, 42).Println("foreground red")
	//
	//color.BgRGB(255, 128, 0).Println("background orange")
	//color.BgRGB(230, 42, 42).Println("background red")
	// 打印日志消息
	Logger.Info("This is an info message")
	Logger.Warn("This is a warning message")
	Logger.Error("This is error")
	//Logger.Error("This is an error message")
	//Logger.Fatal("This is a critical message")
	//Logger.Panic("This is a critical message with panic")
}
